/*
 * JDialogEstructuraPaquete.java
 *
 * Created on 29-jun-2011, 17:34:33
 */
package com.ufps.cuatro.vistas.codificacion;

import java.util.Observer;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import org.jdesktop.application.Action;

import com.ufps.cuatro.CuatroApp;
import com.ufps.cuatro.controlador.render.UtilRender;
import com.ufps.cuatro.modelo.codificacion.PaqueteClass;
import com.ufps.cuatro.modelo.representacion.UtilRepresentacion;
import com.ufps.cuatro.modelo.representacion.componente.ComponenteDistribuidor;
import com.ufps.cuatro.util.Bandera;
import com.ufps.cuatro.util.InformacionNodo;
import com.ufps.cuatro.util.Utileria;
import com.ufps.cuatro.util.generadores.GeneradorArbol;
import com.ufps.cuatro.util.render.MyTreeCellRender;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Catc
 */
public class JDialogEstructuraPaquete extends javax.swing.JDialog {
    private static final long serialVersionUID = 2779948077128043133L;
    
    private Object objParent;
    private Object objSeleccionado;
    private DefaultTreeModel modelTree;   

    /** Creates new form JDialogEstructuraPaquete */
    public JDialogEstructuraPaquete(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setIconImage(Utileria.leerIconoAppEnImagen(Utileria.MODO_16x16).getImage());
    }
    
    /** Creates new form JDialogEstructuraPaquete */
    public JDialogEstructuraPaquete(Object objParent) {
        super(CuatroApp.getApplication().getMainFrame(), true);
        initComponents();        
        this.setIconImage(Utileria.leerIconoAppEnImagen(Utileria.MODO_16x16).getImage());
        this.objParent = objParent;        
        crearArbolEstructuraPaquete();
    }
    
    private boolean crearArbolEstructuraPaquete(){        
        DefaultMutableTreeNode objRaiz = 
                GeneradorArbol.crearEstructura(UtilRepresentacion.objPaqueteRoot);                                   
        JTree objArbol = new JTree(objRaiz);
        modelTree = (DefaultTreeModel) objArbol.getModel();
        this.jTreePaquetes.setModel(modelTree);
        MyTreeCellRender objRender = new MyTreeCellRender(Utileria.ARBOL_ESTRUCTURA_PAQUETES_GUI);
        this.jTreePaquetes.setCellRenderer(objRender);        
        this.jTreePaquetes.setSelectionRow(0);        
        return true;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar2 = new javax.swing.JToolBar();
        jButton4 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jButton5 = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        jButton6 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTreePaquetes = new javax.swing.JTree();
        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabelInfoPath = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Estructura de Paquetes para la Interfaz Gráfica");
        setResizable(false);

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);
        jToolBar2.setBorderPainted(false);
        jToolBar2.setName("jToolBar2"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(JDialogEstructuraPaquete.class, this);
        jButton4.setAction(actionMap.get("aplicar")); // NOI18N
        jButton4.setFocusable(false);
        jButton4.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton4.setName("jButton4"); // NOI18N
        jButton4.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(jButton4);

        jSeparator1.setName("jSeparator1"); // NOI18N
        jToolBar2.add(jSeparator1);

        jButton5.setAction(actionMap.get("close")); // NOI18N
        jButton5.setFocusable(false);
        jButton5.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton5.setName("jButton5"); // NOI18N
        jButton5.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(jButton5);

        jSeparator2.setName("jSeparator2"); // NOI18N
        jToolBar2.add(jSeparator2);

        jButton6.setAction(actionMap.get("help")); // NOI18N
        jButton6.setFocusable(false);
        jButton6.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton6.setName("jButton6"); // NOI18N
        jButton6.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(jButton6);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTreePaquetes.setName("jTreePaquetes"); // NOI18N
        jTreePaquetes.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTreePaquetesValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTreePaquetes);

        jToolBar1.setFloatable(false);
        jToolBar1.setOrientation(javax.swing.SwingConstants.VERTICAL);
        jToolBar1.setName("jToolBar1"); // NOI18N

        jButton1.setAction(actionMap.get("addPaquete")); // NOI18N
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setName("jButton1"); // NOI18N
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton1);

        jButton2.setAction(actionMap.get("editPaquete")); // NOI18N
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setName("jButton2"); // NOI18N
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton2);

        jButton3.setAction(actionMap.get("delPaquete")); // NOI18N
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setName("jButton3"); // NOI18N
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(jButton3);

        jLabelInfoPath.setBackground(new java.awt.Color(255, 255, 225));
        jLabelInfoPath.setText("gui");
        jLabelInfoPath.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabelInfoPath.setName("jLabelInfoPath"); // NOI18N
        jLabelInfoPath.setOpaque(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE)
                    .addComponent(jLabelInfoPath, javax.swing.GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6))
            .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelInfoPath))
                    .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTreePaquetesValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTreePaquetesValueChanged
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) (evt.getPath().getLastPathComponent());
        Object nodeInfo = node.getUserObject();
        InformacionNodo objNodoSeleccionado = (InformacionNodo) nodeInfo;
        try {            
            this.objSeleccionado = objNodoSeleccionado.getObjElemento();
            if (node.isRoot()) {
                //El nodo seleccionado es la raiz del arbol                
            } else if (node.isLeaf()) {
                //El nodo seleccionado es una hoja                
            } else {
                //El nodo seleccionado es una rama                
            }              
            if(this.objSeleccionado instanceof PaqueteClass){
                PaqueteClass objPaquete = (PaqueteClass) objSeleccionado;
                this.jLabelInfoPath.setText(objPaquete.getCanonicalPath());
            }
        } catch (java.lang.ClassCastException ex) {
            Logger.getLogger(JDialogEstructuraPaquete.class.getName()).log(Level.SEVERE, null, ex);            
        }
    }//GEN-LAST:event_jTreePaquetesValueChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JDialogEstructuraPaquete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JDialogEstructuraPaquete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JDialogEstructuraPaquete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JDialogEstructuraPaquete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                JDialogEstructuraPaquete dialog = new JDialogEstructuraPaquete(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    private boolean validarNombrePaquete(String strPaquete){
        if(!Character.isJavaIdentifierStart(strPaquete.charAt(0))){
            UtilRender.msgAdvertencia("El Nombre del Paquete no Inicia con el Estandard java ej: com.ufps.cuatro.", this);
            return false;
        }
        else{
            for(char c : strPaquete.toCharArray()){
                if(!Character.isJavaIdentifierPart(c)){
                    UtilRender.msgAdvertencia("El Nombre del Paquete no es valido con el Estandard java ej: com.ufps.cuatro.", this);
                    return false;
                }
            }
        }
        return true;
    }
    
    @Action
    public void aplicar() {
        UtilRepresentacion.objBibliotecaTrabajoLocal.setObjPaqueteRoot(UtilRepresentacion.objPaqueteRoot);
        Bandera objBandera = new Bandera();
        objBandera.addObserver((Observer) objParent);            
        objBandera.setEstado(Bandera.ACTUALIZAR_ESTRUCTURA_PAQUETES);                                    
        objBandera.notificar();  
        dispose();
        
    }

    @Action
    public void close() {
        if(UtilRender.confirmarCerrarVentana()){
            Bandera objBandera = new Bandera();
            objBandera.addObserver((Observer) objParent);
            objBandera.setEstado(Bandera.PROCESO_CANCELADO);
            objBandera.notificar();
            dispose();
        }
    }

    @Action
    public void help() {
        UtilRender.openDialogHelp(JInternalFrameEstructuraPaquete.class, getTitle());
    }

    @Action
    public void addPaquete() {
        String strPaquete = UtilRender.leerEntradaTexto(this, "Ingrese el Nombre del Paquete: ");
        DefaultMutableTreeNode parentNode = null;        
        TreePath parentPath = jTreePaquetes.getSelectionPath();
        if(strPaquete == null){
            return;
        }                    
        else if(strPaquete.isEmpty()){
            return;
        }         
        else if (parentPath == null) {
            UtilRender.msgAdvertencia("Debe Seleccionar un Paquete Padre.", this);            
            return;
        }
        else if(!validarNombrePaquete(strPaquete)){
            return;
        }
        else {
            parentNode = (DefaultMutableTreeNode) (parentPath.getLastPathComponent());
        }
        strPaquete = strPaquete.toLowerCase();
        InformacionNodo objNodo = (InformacionNodo) parentNode.getUserObject();
        PaqueteClass objPaquetePadre = (PaqueteClass) objNodo.getObjElemento();
        PaqueteClass objNuevo = new PaqueteClass(strPaquete, objPaquetePadre);
        if(objPaquetePadre.addHijo(objNuevo)){
            DefaultMutableTreeNode child = GeneradorArbol.crearNodo(strPaquete, objNuevo);
            modelTree.insertNodeInto(child, parentNode, parentNode.getChildCount());
        }        
        else{
            UtilRender.msgAdvertencia("No se puede Insertar el Paquete en el Destino Actual\nEs Posible que exista un Paquete con ese Nombre en la Estructura.", this);
        }
    }

    @Action
    public void editPaquete() {
        DefaultMutableTreeNode parentNode = null;
        TreePath currentSelection = jTreePaquetes.getSelectionPath();
        if (currentSelection != null) {
            parentNode = (DefaultMutableTreeNode) currentSelection.getLastPathComponent();            
            InformacionNodo objNodo = (InformacionNodo) parentNode.getUserObject();
            PaqueteClass objPaquete = (PaqueteClass) objNodo.getObjElemento();
            if(parentNode.isRoot()){
                UtilRender.msgAdvertencia("No puede Editar el Paquete Raíz.", this);            
                return;
            }            
            String strPaquete = 
                    UtilRender.leerEntradaTexto(this, "Ingrese el Nuevo Nombre para el Paquete [" + objPaquete.getStrNombre() + "] :");            
            if(strPaquete == null){
                return;
            }                    
            else if(strPaquete.isEmpty()){
                return;
            } 
            else if(!validarNombrePaquete(strPaquete)){
                return;
            }
            strPaquete = strPaquete.toLowerCase();                        
            PaqueteClass objPaqueteEdit = (PaqueteClass) objPaquete;
            PaqueteClass objPaquetePadre = objPaquete.getObjRoot();
            if(objPaquetePadre.getHijo(strPaquete) != null){
                UtilRender.msgAdvertencia("El Identificador Ingresado ha sido utilizado previamente en un Paquete.", this);
                return;
            }
            objPaqueteEdit.setStrNombre(strPaquete);                                    
            parentNode.setUserObject(new InformacionNodo(strPaquete, objPaqueteEdit));                        
            modelTree.nodeChanged(parentNode);            
        }
        else{
            UtilRender.msgAdvertencia("Debe Seleccionar un Paquete.", this);            
        }
    }

    @Action
    public void delPaquete() {
        DefaultMutableTreeNode parentNode = null;
        TreePath currentSelection = jTreePaquetes.getSelectionPath();
        if (currentSelection != null) {
            parentNode = (DefaultMutableTreeNode) currentSelection.getLastPathComponent();
            
            if(parentNode.isRoot()){
                UtilRender.msgAdvertencia("No puede Eliminar el Paquete Raíz.", this);            
                return;
            }
            
            InformacionNodo objNodo = (InformacionNodo) parentNode.getUserObject();
            PaqueteClass objPaquete = (PaqueteClass) objNodo.getObjElemento();
            //Validar inclusion del paquete en contenedores
            for(ComponenteDistribuidor objComponente : UtilRepresentacion.objBibliotecaTrabajoLocal.getObjComponentesContenedores()){
                if(objComponente.getStrPaquete().equals(objPaquete.getStrNombre())){
                    UtilRender.msgAdvertencia("No puede Eliminar un Paquete Inicializado.\nElimine las Referecnias ej: " + objComponente.getName(), this);            
                    return;
                }
            } 
            
            for(ComponenteDistribuidor objComponente : UtilRepresentacion.objBibliotecaTrabajoLocal.getObjComponentesIntegradores()){
                if(objComponente.getStrPaquete().equals(objPaquete.getStrNombre())){
                    UtilRender.msgAdvertencia("No puede Eliminar un Paquete Inicializado.\nElimine las Referecnias ej: " + objComponente.getName(), this);            
                    return;
                }
            }
            
            if(!UtilRender.msgConfirmar("¿Desea Eliminar el Paquete Seleccionado?", this)){
                return;
            }                      
            DefaultTreeModel model = ((DefaultTreeModel) jTreePaquetes.getModel());
            model.removeNodeFromParent(parentNode);
            PaqueteClass objPaqueteRoot = objPaquete.getObjRoot();
            objPaqueteRoot.delHijo(objPaquete);
        }
        else{
            UtilRender.msgAdvertencia("Debe Seleccionar un Paquete.", this);            
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabelInfoPath;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JTree jTreePaquetes;
    // End of variables declaration//GEN-END:variables
}
